import axios from 'axios'
import { ElMessage } from 'element-plus'
import { getToken } from './token'


const axiosConfig = {
    headers: {
        'Content-Type': 'application/json'
    },
    baseURL: import.meta.env.VITE_API_BASE_URL || 'http://127.0.0.1:8000',
    timeout: 10000,
    // 添加重试配置
    retry: 3,
    retryDelay: 1000
  }

const instance = axios.create(axiosConfig);

// 添加请求拦截器
instance.interceptors.request.use(
    config => {
        // 从浏览器的 cookie 中获取 token
        const token = getToken();
        if (token) {
        config.headers.Authorization = `EX ${token}`;
        }
        return config;
    },
    error => {
        return Promise.reject(error);
    }
);

// 添加响应拦截器
instance.interceptors.response.use(
    response => {
        if (response.data.status === 200) {
            console.log('请求成功：', response.data);
            return response.data.data;
        } else {
            ElMessage.error('发生错误：' + response.data.error);
            return Promise.reject(response);
        }
    },
    error => {
        if (!error.response) {
            ElMessage.error('网络错误，请检查您的网络连接');
            return Promise.reject(error);
        }

        switch (error.response.status) {
            case 401:
                ElMessage.error('未授权，请重新登录');
                // 这里可以添加跳转到登录页的逻辑
                break;
            case 403:
                ElMessage.error('拒绝访问');
                break;
            case 404:
                ElMessage.error('请求的资源不存在');
                break;
            case 500:
                ElMessage.error('系统内部错误');
                break;
            default:
                ElMessage.error('发生错误：' + error.message);
        }

        // 实现请求重试
        const config = error.config;
        if (!config || !config.retry) return Promise.reject(error);

        config.__retryCount = config.__retryCount || 0;

        if (config.__retryCount >= config.retry) {
            return Promise.reject(error);
        }

        config.__retryCount += 1;

        const backoff = new Promise(resolve => {
            setTimeout(() => {
                resolve();
            }, config.retryDelay || 1000);
        });

        return backoff.then(() => {
            return instance(config);
        });
    }
);

// 添加请求取消方法
export const cancelRequest = (requestId) => {
    const controller = new AbortController();
    instance.defaults.signal = controller.signal;
    return controller;
};

export default instance;